package cn.kent.context;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.time.chrono.IsoChronology;
import java.util.HashMap;

public class MySessionContext {

    private static MySessionContext instance;
    // session Map 用来存储session，如果session较多，影响到系统性能的话，可以把redis，key-val
    // sessionId -> session对象 session对象序列化
    public static HashMap<String , HttpSession> sessionMap;

    private MySessionContext(){
        sessionMap = new HashMap<String, HttpSession>();
    }


    /**
     * 单例
     */
    public static MySessionContext getInstance() {
        if (instance == null) {
            instance = new MySessionContext();
        }
        return instance;
    }

    /**
     * 添加session
     */
    public synchronized void addSession(HttpSession session){
        if (session != null) {
            System.out.println("session添加成功！");
            sessionMap.put(session.getId(), session);
        }
    }

    /**
     * 删除session
     */
    public synchronized void delSession(HttpSession session){
        if (session != null) {
            System.out.println("session删除成功！");
            sessionMap.remove(session.getId());
        }
    }

    /**
     * 根据sessionId获取session
     */
    public synchronized HttpSession getSession(String sessionId){
        if (sessionId == null) {
            return null;
        }
        return sessionMap.get(sessionId);
    }

}
